package com.company.cloud.common.auth.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.auth.bean.WebRequestUrlModel;
import com.company.cloud.common.constant.ApiAuthTypeEnum;

public class WebRequestUrlUtils {
	
	public static List<WebRequestUrlModel> getWebRequestUrls(RequestMappingHandlerMapping rmhm){
		List<WebRequestUrlModel> data=new ArrayList<WebRequestUrlModel>();
		if(rmhm==null) {
			return data;
		}
		Map<RequestMappingInfo, HandlerMethod> handlerMethodsMap = rmhm.getHandlerMethods();
		
		for (Map.Entry<RequestMappingInfo, HandlerMethod> item : handlerMethodsMap.entrySet()) {
			WebRequestUrlModel  dataItem=new WebRequestUrlModel();
			
			RequestMappingInfo info = item.getKey();
			HandlerMethod method = item.getValue();
//			dataItem.setClassName(method.getMethod().getDeclaringClass().getName());
//			dataItem.setMethodName(method.getMethod().getName());
			PatternsRequestCondition p = info.getPatternsCondition();
			for (String url : p.getPatterns()) {
				dataItem.setMethodUrl(url);
			}
			
//			RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
//			String type = methodsCondition.toString();
//			if (type != null && type.startsWith("[") && type.endsWith("]")) {
//				type = type.substring(1, type.length() - 1);
//				dataItem.setMethodType(type);
//			}else {
//				dataItem.setMethodType(type);
//			}
			
			Class<?> classType=method.getBeanType();
        	if(method.getMethodAnnotation(Login.class) !=null || classType.getAnnotation(Login.class) !=null) {
        		dataItem.setAuthType(ApiAuthTypeEnum.Login_List.getCode());
        	}else if(method.getMethodAnnotation(Authc.class) !=null || classType.getAnnotation(Authc.class) !=null) {
        		dataItem.setAuthType(ApiAuthTypeEnum.Auth_List.getCode());
        	}else {
        		dataItem.setAuthType(ApiAuthTypeEnum.White_List.getCode());
        	}
			data.add(dataItem);
		}
		
		
		return data;
	}

}
